/**
 * Created by ltx on 2017/9/20.
 */
const express=require('express');
const mysql=require('mysql');

var db=mysql.createPool({host: 'localhost', user: 'root', password: '123456*', database: 'myblog'});


module.exports=function (){
    var router=express.Router();

    router.post('/register', (req, res,next)=>{
       // console.log(req.body);
        var username=req.body.username;
        var password=req.body.password;
        var repassword=req.body.repassword;
        //console.log(req.body);

        //用户是否为空
        if (username==''){
            res.json({
                code:1,
                message:'用户名不能为空'
            });
            return;
        }
        //密码是否为空
        else if (password==''){
            res.json({
                code:2,
                message:'密码不能为空'
            });
            return;
        }
        //两次输入的密码不一致
        else if (password!=repassword){
            res.json({
                code:3,
                message:'两次输入的密码不一样耶'
            });
            return;
        }
        else {
            db.query(`SELECT * FROM user_table WHERE name='${req.body.username}'`,(err,data)=>{
                console.log(data);
                if (err){
                    res.status(500).send('数据库错误').end();
                }
                else {
                    //res.send(data).end();
                    if (data!=''){
                        res.json({
                            code:4,
                            message:'你来晚啦，该名已经被注册了'
                        });
                    }
                    else {
                        db.query(`INSERT INTO user_table (name, password)
            VALUES('${username}', '${password}')`, (err, data)=>{
                            if (err){
                                res.status(500).send('数据库增加失败').end();
                            }
                            else {
                                res.json({
                                    code:0,
                                    message:'注册成功'
                                });
                                return;
                            }
                        })
                    }
                }
            })
        }
    });

    return router;
};